package com.cloud.pole.advert.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.cloud.pole.common.handler.GlobalExceptionHandler;
import com.cloud.pole.common.interceptor.AdminAuthRestInterceptor;
import com.cloud.pole.common.interceptor.ClientTokenInterceptor;
import com.cloud.pole.common.interceptor.ServiceAuthRestInterceptor;
import com.cloud.pole.common.interceptor.UserAuthRestInterceptor;
import java.util.ArrayList;
import java.util.Collections;

@Configuration("advertWebConfig")
@Primary
public class WebConfiguration extends WebMvcConfigurerAdapter {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 客户端调用需要过滤的(需要过滤token和client-token)
		/*网关上增加了参数client-token，防止从微服务端口直接访问*/
		registry.addInterceptor(getServiceAuthRestInterceptor())
				.addPathPatterns(getClientPathPatterns().toArray((new String[] {})))
				.addPathPatterns(getFrontPathPatterns().toArray(new String[] {}))
				.addPathPatterns(getAdminPathPatterns().toArray(new String[] {}));
		// 前端调用需要过滤的
		registry.addInterceptor(getUserAuthRestInterceptor()).addPathPatterns(getFrontPathPatterns().toArray(new String[] {}));
		// 后台调用需要过滤
		registry.addInterceptor(getAdminAuthRestInterceptor()).addPathPatterns(getAdminPathPatterns().toArray(new String[] {}));
	}

	@Bean
	ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
		return new ServiceAuthRestInterceptor();
	}

	@Bean
	UserAuthRestInterceptor getUserAuthRestInterceptor() {
		return new UserAuthRestInterceptor();
	}

	@Bean
	AdminAuthRestInterceptor getAdminAuthRestInterceptor() {
		return new AdminAuthRestInterceptor();
	}

	/**
	 * 需要用户和服务认证判断的路径（前端）
	 * 
	 * @return
	 */
	private ArrayList<String> getFrontPathPatterns() {
		ArrayList<String> list = new ArrayList<>();
		String[] urls = { "/暂无需要设置的地址/**"};
		Collections.addAll(list, urls);
		return list;
	}

	/**
	 * 需要用户和服务认证判断的路径（后台地址）
	 * 
	 * @return
	 */
	private ArrayList<String> getAdminPathPatterns() {
		ArrayList<String> list = new ArrayList<>();
		String[] urls = { "/暂无需要设置的地址/**" };
		Collections.addAll(list, urls);
		return list;
	}

	/**
	 * 需要用户和服务认证判断的路径(客户端)
	 * 
	 * @return
	 */
	private ArrayList<String> getClientPathPatterns() {
		ArrayList<String> list = new ArrayList<>();
		String[] urls = { "/api/Advert/**" };
		Collections.addAll(list, urls);
		return list;
	}
}
